/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fuzzy.actions;

import fuzzy.hibernate.HibernateUtil;
import fuzzy.hibernate.Uzytkownicy;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author kaqu
 */
public class CreditAction extends DispatchAction {

    /* forward name="success" path="" */
    private static final String VAL_EXACTLY = "Exactly";
    private static final String VAL_CLOSE = "More or less";
    private static final String VAL_ABOUT = "About";

    public ActionForward enter(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("done!");//TODO

        CreditForm f = (CreditForm) form;
        if (f != null) {
           // System.out.println(f.getClientID() != null ? f.getClientID() : "");
            System.out.println(f.getIncome());
            System.out.println(f.getIncomeFuzzy());
            System.out.println(f.getOutcome());
            System.out.println(f.getOutcomeFuzzy());

        }

        return mapping.findForward("new");
    }

    public ActionForward unregisteredCreditCheck(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        
       
        System.out.println("CHECKED AJAX");
        CreditForm ajaxForm = (CreditForm) form;
        
        
        String idClienta = ajaxForm.getClientID();
        System.out.println("Id klienta: "+idClienta);
        int ifuzzy, ofuzzy, cfuzzy, nfuzzy, mfuzzy;
        ifuzzy = getFuzzyValue(ajaxForm.getIncomeFuzzy());
        ofuzzy = getFuzzyValue(ajaxForm.getOutcomeFuzzy());
        cfuzzy = getFuzzyValue(ajaxForm.getOtherCreditsFuzzy());
        nfuzzy = getFuzzyValue(ajaxForm.getNeededCreditFuzzy());
        mfuzzy = getFuzzyValue(ajaxForm.getMonthsFuzzy());
        List result;
        response.setContentType("text/text;charset=utf-8");

        response.setHeader("cache-control", "no-cache");
        System.out.println(ajaxForm.getIncomeFuzzy());
        Query query;
        Session session = HibernateUtil.getSession();
       
        
        if(idClienta !=null && !idClienta.equals("admin") && !idClienta.equals("konsultant")){
            BigDecimal id;
            BigDecimal in,out,other;
            query = session.createSQLQuery("SELECT idklienta FROM uzytkownicy NATURAL JOIN klienci WHERE login='"+idClienta+"'");
            result = query.list();
            id = (BigDecimal) result.get(0);
            System.out.println("nie jest nulll"+id);
            
            //other
            query = session.createSQLQuery("select distinct SUM(k.MIESIECZNARATA) OVER (PARTITION BY d.idklienta) as sumarat\n" +
              "from DYSPOZYCJA d join RACHUNEK r on (d.IDRACHUNKU=r.IDRACHUNKU) right join kredyt k on (r.IDRACHUNKU=k.IDRACHUNKU) \n" +
              "where k.STATUS='active' and idklienta="+id);
            result = query.list();
            if(result.isEmpty())
            {
                other = new BigDecimal(0);
            }
            else
            {
               other = (BigDecimal)result.get(0);
            }
            
            System.out.println(other);
            //out
            query = session.createSQLQuery("select distinct (SUM(kwota) OVER (PARTITION BY d.idklienta)) as sumarozchodow\n" +
              "from DYSPOZYCJA d join RACHUNEK r on (d.IDRACHUNKU=r.IDRACHUNKU) right join TRANSAKCJA t on (r.IDRACHUNKU=t.IDRACHUNKU) \n" +
              "where t.RODZAJOPERACJI='out' and idklienta="+id);
            
            result = query.list();
            System.out.println(result);
            if(result.isEmpty())
            {
                out = new BigDecimal(0);
            }
            else
            {
               out = (BigDecimal)result.get(0);
            }
            System.out.println(out);
            //other
            query = session.createSQLQuery("select distinct (SUM(kwota) OVER (PARTITION BY d.idklienta)) as sumaprzychodow\n" +
              "from DYSPOZYCJA d join RACHUNEK r on (d.IDRACHUNKU=r.IDRACHUNKU) right join TRANSAKCJA t on (r.IDRACHUNKU=t.IDRACHUNKU) \n" +
              "where t.RODZAJOPERACJI='in' and idklienta="+id);
            result = query.list();
            if(result.isEmpty())
            {
                in = new BigDecimal(0);
            }
            else
            {
                in = (BigDecimal)result.get(0);
            }
            System.out.println(in);
            
            query = session.createSQLQuery(
                "SELECT GETFUZZYCREDITANSWER( :income , :incomefuzzy , :outcome , :outcomefuzzy , :otherCredit , :otherCreditFuzzy , :months , :monthsfuzzy , :neededCredit , :neededCreditfuzzy  ) FROM dual")
                .setParameter("income", in).setParameter("incomefuzzy", ifuzzy).setParameter("outcome", out).setParameter("outcomefuzzy", ofuzzy).setParameter("otherCredit", other).setParameter("otherCreditFuzzy", cfuzzy).setParameter("neededCredit", ajaxForm.getNeededCredit()).setParameter("neededCreditfuzzy", nfuzzy).setParameter("months", ajaxForm.getMonths()).setParameter("monthsfuzzy", mfuzzy);
          
        }
        else
        {
           System.out.println("jest nulll");
            query = session.createSQLQuery(
                "SELECT GETFUZZYCREDITANSWER( :income , :incomefuzzy , :outcome , :outcomefuzzy , :otherCredit , :otherCreditFuzzy , :months , :monthsfuzzy , :neededCredit , :neededCreditfuzzy  ) FROM dual")
                .setParameter("income", ajaxForm.getIncome()).setParameter("incomefuzzy", ifuzzy).setParameter("outcome", ajaxForm.getOutcome()).setParameter("outcomefuzzy", ofuzzy).setParameter("otherCredit", ajaxForm.getOtherCredits()).setParameter("otherCreditFuzzy", cfuzzy).setParameter("neededCredit", ajaxForm.getNeededCredit()).setParameter("neededCreditfuzzy", nfuzzy).setParameter("months", ajaxForm.getMonths()).setParameter("monthsfuzzy", mfuzzy);
         
        }
        result = query.list();
        
        System.out.println("result " + result.size());
        System.out.println("result " + result);
        System.out.println("result " + result.get(0));
        PrintWriter out = response.getWriter();
        if(result.get(0)==null)
        {
            out.println("There is no chance for this credit.");
        }
        else
        {
            out.println(result.get(0));
        }
        
        out.flush();
        return null;
    }

    private int getFuzzyValue(String str) {
        if (str.equals(VAL_ABOUT)) {
            return 2;
        } else if (str.equals(VAL_CLOSE)) {
            return 1;
        } else {
            return 0;
        }
    }

}
